import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './resolutionComps/index.less';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { ModalC,FirstHeaderC } from '../../../comps';
import dictData from './resolutionComps/dictConfig';
import { fixedNum, getProductName } from '../../../utils/utils';
import config from '../../../comps/business/tradingDirect/config';
import { direct as otherConfig } from '../../../comps/business/tradingDirect/otherConfig';
import configMarket from '../../../comps/business/tradingMarket/config';
import SplitTableC from './resolutionComps/splitTableC';
import SplitTableBankC from './resolutionComps/SplitTableBankC';
import uuid from 'es6-uuid';
@Form.create()
class ResolutionC extends PureComponent {
  state = {
    portfolioTree: [], //产品组id下对应的组合树
    dataSource: [], //拆分表格的初始化数据
    assignFee: 0.0, //已分配费用
  };
  UNSAFE_componentWillMount() {
    this.props.tradeInfo.zgPledgeVo && this.props.tradeInfo.zgPledgeVo.map((item) => (item.id = uuid(32)));
  }
  componentDidMount() {
    const jg = [
      { title: '中债', value: '309904' },
      { title: '上清', value: '549888' },
    ];
    this.props.tradeInfo.clientName = getProductName(this.props.tradeInfo.clientCode, jg);
    if (this.props.isEdit) {
      //回填详情
      this.querySplitTableList();
      this.setState({
        assignFee: Number(this.props.tradeInfo.fee).toFixed(2),
      });
    } else {
      if (this.props.tradeInfo.orderType == '4' && this.props.tradeInfo.direction == 2) this.getBuyBackInfo(); //融资回购单独请求 方便默认展开
      this.getPortfolio();
    }
  }
  //查询融资回购 拆分时表格数据
  getBuyBackInfo = () => {
    this.setState({ loadingStatus: true });
    this.props.dispatch({
      type: 'orderSplitM/getBuyBackInfo',
      payload: { tradeInfoId: this.props.tradeInfo.id },
      callback: (data) => {
        if (data) {
          data.map((item) => {
            item.key = uuid(32);
            item.id = item.productId;
            item.info &&
              item.info.map((child) => {
                child.key = uuid(32);
                child.name = child.tradingcode + '-' + child.secuabbr;
                child.isEdit = false;
                child.pid = item.key;
                this.props.tradeInfo.zgPledgeVo.map((zgp) => {
                  //为了上表 和下表质押券的id一致
                  if (child.name == zgp.tradingcode + '-' + child.secuabbr) {
                    child.id = zgp.id;
                  }
                });
              });
            let nestedConfig = {
              dataSource: item.info,
              rowKey: 'key',
              columns: this.state.splitRef.childColumns(),
              hidePage: true,
            };
            item.nestedConfig = nestedConfig;
            delete item.info;
          });
        }
        this.setState({
          dataSource: data || [],
          loadingStatus: false,
        });
      },
    });
  };
  //查询详情
  querySplitTableList = () => {
    if (this.props.tradeInfo.orderType != '4') {
      this.props.dispatch({
        type: 'orderSplitM/querySplitTableList1',
        payload: {
          tradeInfoId: this.props.tradeInfo.id,
          js: this.props.settlement ? '1' : '',
        },
        callback: (data) => {
          if (data && this.props.settlement) {
            data.map((item) => {
              item.instructionStatus = item.instructionStatus == 7 ? '已交收' : item.instructionStatus == 6 ? '未交收' : item.instructionStatus;
            });
          }
          this.setState({
            dataSource: data || [],
          });
        },
      });
    } else {
      //回购
      this.props.dispatch({
        type: 'orderSplitM/querySplitTableList2',
        payload: {
          tradeInfoId: this.props.tradeInfo.id,
          js: this.props.settlement ? '1' : '',
        },
        callback: (data) => {
          if (data) {
            data.map((item) => {
              item.instructionStatus = item.instructionStatus == 7 ? '已交收' : item.instructionStatus == 6 ? '未交收' : item.instructionStatus;
              item.info &&
                item.info.map((child) => {
                  child.key = uuid(32);
                  child.name = child.tradingcode + '-' + child.secuabbr;
                });
              let nestedConfig = {
                dataSource: item.info,
                rowKey: 'key',
                columns: this.state.splitRef.childColumns(),
                hidePage: true,
              };
              item.nestedConfig = nestedConfig;
              delete item.info;
            });
          }
          this.setState({
            dataSource: data || [],
          });
        },
      });
    }
  };
  //批量查询资金
  queryFundList = (idList, dataSource) => {
    let p = new Promise((res, rej) => {
      this.props.dispatch({
        type: 'orderSplitM/queryFundList',
        payload: [...idList],
        callback: (data) => {
          dataSource.map((item) => {
            data.map((x) => {
              if (item.productId == x.nodeId) {
                item.t0 = x.t0;
                item.t1 = x.t1;
              }
            });
          });
          this.setState({
            fundList: data, //存入所有组合的可用金额
          });
          res(dataSource);
        },
      });
    });
    return p;
  };
  //批量查询持仓
  queryPositongList = (idList) => {
    var arr = [];
    if (this.props.tradeInfo.orderType == '4') {
      if (!this.props.tradeInfo.zgPledgeVo) return;
      let zgPledgeVo = this.props.tradeInfo.zgPledgeVo;
      idList.map((itemId) => {
        //回购查询每个质押券的持仓
        zgPledgeVo.map((item) => {
          arr.push({
            tradingcode: item.tradingcode,
            exchangecode: itemId.exchangecode,
            fundId: itemId.fundId,
          });
        });
      });
    }
    let querys = this.props.tradeInfo.orderType == '4' ? arr : [...idList];
    let p = new Promise((res, rej) => {
      this.props.dispatch({
        type: 'orderSplitM/queryPositongList',
        payload: [...querys],
        callback: (data) => {
          res(data);
        },
      });
    });
    return p;
  };

  formatData = (data) => {
    data.map((item) => {
      item.title = item.name;
      item.value = item.id;
      if (item.children) {
        this.formatData(item.children);
      }
    });
  };
  //查询到组合树
  getPortfolio = () => {
    let tradeInfo = this.props.tradeInfo || {};
    if (this.props.tradeInfo.orderType != '4' || (this.props.tradeInfo.orderType == '4' && this.props.tradeInfo.direction == 1)) {
      this.setState({ loadingStatus: true });
    }
    this.props.dispatch({
      type: 'orderSplitM/queryPortfolioList',
      payload: {
        groupId: this.props.tradeInfo.productGroupId,
      },
      callback: (data) => {
        if (data) {
          let myIdList = this.treeToArr(data); //树形转成数组
          const dataSource = [];
          this.formatData(data);
          let idList = [];
          myIdList.forEach((item) => {
            idList.push({
              tradingcode: tradeInfo.tradingcode,
              exchangecode: tradeInfo.exchangecode,
              fundId: item,
            });
          });
          data.map((item) => {
            let obj = {
              productId: item.id,
              tradeNum: 0,
              tradePrice: this.props.tradeInfo.direction == 4 ? null : 0,
              name: item.name,
              isEdit: false,
              key: uuid(32),
            };
            dataSource.push(obj);
          });
          Promise.all([this.queryFundList(myIdList, dataSource), this.queryPositongList(idList)]).then((res) => {
            let data1 = [];
            if (this.props.tradeInfo.orderType != '4') {
              res[0] &&
                res[0].map((item) => {
                  res[1] &&
                    res[1].map((x) => {
                      if (x.fundId == item.productId) {
                        item.available = x.available;
                        item.hold = x.hold;
                      }
                    });
                });
            }
            this.setState({
              holdList: res[1],
            });

            data1 = res[0];
            if (this.props.tradeInfo.orderType == '4' && this.props.tradeInfo.direction == 2) {
              this.setState({
                portfolioTree: data,
              });
            } else {
              this.setState({
                portfolioTree: data,
                dataSource: data1 ? [...data1] : [],
              });
            }
            if (this.props.tradeInfo.orderType != '4' || (this.props.tradeInfo.orderType == '4' && this.props.tradeInfo.direction == 1)) this.setState({ loadingStatus: false });
          });
        } else {
          if (this.props.tradeInfo.orderType != '4' || (this.props.tradeInfo.orderType == '4' && this.props.tradeInfo.direction == 1)) this.setState({ loadingStatus: false });
          this.setState({
            portfolioTree: [],
            dataSource: [],
          });
        }
      },
    });
  };
  treeToArr = (data) => {
    //树形转数组
    const result = [];
    data.forEach((item) => {
      const loop = (data) => {
        let id = data.id;
        result.push(id);
        let child = data.children;
        if (child) {
          for (let i = 0; i < child.length; i++) {
            loop(child[i]);
          }
        }
      };
      loop(item);
    });
    return result;
  };
  //确定 保存在前台数据
  onOK = () => {
    if (this.props.isEdit && this.props.settlement) {
      //交收状态下
      this.props.dispatch({
        type: 'moreFundsOrderM/settlementModalData',
        payload: {
          tradeInfoId: this.props.tradeInfo.id,
        },
        callback: (data) => {
          if (data) {
            this.props.onOk();
          } else {
            return;
          }
        },
      });
      return;
    } else if (this.props.isEdit) {
      //详情状态下
      this.props.onCancel();
      return;
    }

    if (this.props.tradeInfo.orderType != '4') {
      //理财直融 非标 债券
      const data = this.state.splitRef.submit();
      if (data && data.length) {
        this.props.dispatch({
          type: 'orderSplitM/splitSave1',
          payload: {
            tradeInfoId: this.props.tradeInfo.id,
            splitList: data,
          },
          callback: (type) => {
            if (type) {
              this.props.onOk();
            }
          },
        });
      }
    } else {
      //银行间回购
      const data = this.state.splitRef.submit();
      if (data && data.length) {
        let splitList = [];
        data.map((item) => {
          let row = _.cloneDeep(item);
          row.info = item.nestedConfig.dataSource;
          delete row.nestedConfig;
          splitList.push(row);
        });
        this.props.dispatch({
          type: 'orderSplitM/splitSave2',
          payload: {
            tradeInfoId: this.props.tradeInfo.id,
            splitList: splitList,
          },
          callback: (type) => {
            if (type) {
              this.props.onOk();
            }
          },
        });
      }
    }
  };
  //拿到对应的信息
  getData(value, type) {
    let data;
    dictData.orderType.map((item) => {
      if (item.value == value) {
        data = item[type];
      }
    });
    return data;
  }
  // 找到指定业务类型对应的交易方向下拉
  getDirectData = (businessType) => {
    let ds = config.filter((item) => item.value == businessType);
    if (ds && ds.length > 0) {
      let tradingDirect = [];
      // 遍历交易方向，判断该交易方向在当前的业务下是否需要展示
      ds[0].tradingDirect.forEach((element) => {
        tradingDirect.push(element);
      });
      return tradingDirect;
    } else {
      ds = otherConfig.filter((item) => item.value == businessType);
      if (ds && ds.length > 0) return ds[0].tradingDirect;
    }
    return [];
  };
  //获取交易市场名称
  getExchangeData = (value) => {
    var str;
    configMarket.map((item) => {
      if (item.value == value) str = item.title;
    });
    return str;
  };

  //字典翻译 交易方向 交易市场
  transfer = (type, value) => {
    const { tradeInfo } = this.props;
    if (type == 'direction') {
      let arr = this.getDirectData(this.getData(tradeInfo.orderType, 'businessType'));
      return getProductName(value, arr);
    } else {
      return this.getExchangeData(value);
    }
  };

  //展示交易信息
  rendertradeInfo = () => {
    const { tradeInfo } = this.props;
    const { assignFee } = this.state;
    const info = dictData[this.getData(tradeInfo.orderType, 'info')];
    const qssd = [
      { title: 'T+0', value: '1' },
      { title: 'T+1', value: '2' },
    ];
    return (
      <div className={myStyle.tradeInfo}>
        {info &&
          info.map((item, index) => {
            var isTransfer = item.isTransfer;
            return (
              <div key={index} className={myStyle.item}>
                <span>{item.title}:</span>
                {isTransfer ? (
                  <span>{tradeInfo[item.key] == null ? '--' : this.transfer(item.key, tradeInfo[item.key]) || '--'}</span>
                ) : (
                  <span title={item.hidden ? tradeInfo[item.key] : ''} className={item.hidden ? myStyle.spanHidden : ''}>
                    {tradeInfo[item.key] == null ? '--' : item.number != undefined ? fixedNum(Number(tradeInfo[item.key])) : tradeInfo[item.key]}
                    {tradeInfo[item.key] == null ? null : item.unit}
                  </span>
                )}
              </div>
            );
          })}
        {tradeInfo.settlementSpeed !== undefined && (
          <div className={myStyle.item}>
            <span>清算速度:</span>
            <span>{tradeInfo.settlementSpeed == null ? '--' : getProductName(tradeInfo.settlementSpeed, qssd)}</span>
          </div>
        )}
        <div className={myStyle.item}>
          <span>费用:</span>
          {tradeInfo.fee == null ? (
            <span>--</span>
          ) : (
            <span>
              {fixedNum(Number(tradeInfo.fee))}元<span style={{ margin: '0 6px' }}>{`(${fixedNum(assignFee)}/${fixedNum(Number(tradeInfo.fee))})`}</span>
            </span>
          )}
        </div>
      </div>
    );
  };
  //变更费用
  feeChange = (num) => {
    this.setState({
      assignFee: num,
    });
  };
  render() {
    const { tradeInfo, visible, loading, settlement } = this.props;
    const { dataSource, portfolioTree } = this.state;
    const modalProps = {
      visible: visible,
      onOk: this.onOK,
      onCancel: () => {
        this.props.onCancel();
      },
      title: this.props.settlement ? '交收' : this.getData(tradeInfo.orderType, 'title') + '拆分',
      confirmLoading:
        loading.effects['orderSplitM/splitSave1'] == true || loading.effects['orderSplitM/splitSave2'] == true || loading.effects['moreFundsOrderM/settlementModalData'] == true,
      className: myStyle.split,
      width: 1240,
      footer: this.props.isEdit ? (this.props.settlement ? undefined : null) : undefined,
      maskClosable: false,
    };
    return (
      <ModalC {...modalProps}>
        <FirstHeaderC title='多基金簿记' />
        {this.rendertradeInfo()}
        {this.props.tradeInfo.orderType != '4' && (
          <SplitTableC
            dataSource={dataSource}
            portfolioTree={portfolioTree}
            tradeInfo={tradeInfo}
            feeChange={this.feeChange}
            onRef={(ref) => {
              this.setState({ splitRef: ref });
            }}
            isDetail={this.props.isEdit}
            settlement={settlement}
            fundList={this.state.fundList}
            holdList={this.state.holdList}
            loadingStatus={this.state.loadingStatus}
          />
        )}
        {this.props.tradeInfo.orderType == '4' && (
          <SplitTableBankC
            dataSource={dataSource}
            portfolioTree={portfolioTree}
            tradeInfo={tradeInfo}
            feeChange={this.feeChange}
            onRef={(ref) => {
              this.setState({ splitRef: ref });
            }}
            isDetail={this.props.isEdit}
            settlement={settlement}
            holdList={this.state.holdList}
            fundList={this.state.fundList}
            loadingStatus={this.state.loadingStatus}
          />
        )}
      </ModalC>
    );
  }
}
export default connect(({ orderSplitM, moreFundsOrderM, loading }) => ({
  orderSplitM,
  moreFundsOrderM,
  loading,
}))(ResolutionC);
